package com.primecodegen.util;

import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ResourceManager {

    util ut = new util();
    private static String JDBC_DRIVER = util.getBundleValue("JDBC_DRIVER");
    private static String JDBC_URL = util.getBundleValue("JDBC_URL");
    private static String JDBC_USER = util.getBundleValue("JDBC_USER");
    private static String JDBC_PASSWORD = util.getBundleValue("JDBC_PASSWORD");
    private static Driver driver = null;
    private static DataSource ds;

    public static synchronized Connection getConnection() throws Exception {
        try {

            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/" + util.getBundleValue("DATASOURCE"));

        } catch (NamingException e) {
            e.printStackTrace();
        }
        if (ds == null) {
            throw new Exception("ds 'DataSource' is null");
        } else {
            return ds.getConnection();
        }

    }


    public static void close(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
               
            }
        } catch (SQLException sqle) {
            System.out.println("Exception Closing connection");
            sqle.printStackTrace();
        }
    }

    public static void close(PreparedStatement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException sqle) {
            System.out.println("Exception Closing PreparedStatement");
            sqle.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException sqle) {
            System.out.println("Exception Closing ResultSet");
            sqle.printStackTrace();
        }

    }

//    public static synchronized Connection getDirectConnection()
//
//    {
//        try {
//            if (driver == null) {
//                try {
//                    Class<?> jdbcDriverClass = Class.forName(JDBC_DRIVER);
//                    driver = (Driver) jdbcDriverClass.newInstance();
//                    DriverManager.registerDriver(driver);
//                } catch (Exception e) {
//                    System.out.println("Failed to initialise JDBC driver");
//                    e.printStackTrace();
//                }
//            }
//            return DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
//        } catch (SQLException ex) {
//            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }
}
